package cn.net.xyan.blossom.core.utils

import javax.servlet.http.HttpServletRequest
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes

fun httpServletRequest(): HttpServletRequest? {
    return try {
        val curRequest = (RequestContextHolder.currentRequestAttributes() as ServletRequestAttributes?)
                ?.request
        curRequest
    }catch (e:Throwable){
        null
    }

}

fun remoteAddr(): String? {
    return httpServletRequest()?.remoteAddr
}

fun absolutePath(path: String): String {
    return contextPath() + path
}

fun absoluteURL(path: String): String {
    return appRootURL() + path
}

fun contextPath(): String? {
    val request = httpServletRequest()
    var contextPath = request?.contextPath
    if ("/" == contextPath) {
        contextPath = ""
    }
    return contextPath
}

fun appRootURL(): String {
    val request = httpServletRequest()
    val scheme = request?.scheme
    val host = request?.serverName
    val port = request?.serverPort
    var needPort = true
    if ("http" == scheme && port == 80 || "https" == scheme && port == 443) {
        needPort = false
    }

    var sPort = String.format(":%d", port)
    if (!needPort)
        sPort = ""

    return String.format("%s://%s%s%s", scheme, host, sPort, contextPath())
}
